'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'

import {
    HttpService,
    Toast,
    getLocalTime
} from '../Http';

import {
    loginJxt,
    goJxtUrl,
    integralSwitch,
    AjaxUploadImgUrl
} from '../Tool'


import imgHead from '../img/other/headerImgDefault.png'
import $ from 'jquery'

export default class New extends React.Component {

    constructor(props) {
        super(props);
        this.jxtBabyId = null
        this.state = {
            dataLoad: 1,
            dataNull: 0,
            dataList: []
        }
    }

    componentWillMount() {
        if (this.props.sign) {
            this.jxtBabyId = this.props.sign
            this.loadData()
        }
    }

    componentDidMount() {
        setTimeout(() => {
            if (this.state.dataLoad == 1)
                this.loadData()
        }, 5000)
        clearInterval(sessionStorage.newsTimer)
        sessionStorage.newsTimer = setInterval(() => {
            if (location.href.indexOf('map') > -1 || location.href.indexOf('teacher') > -1)
                this.getList()
        }, 1000 * 60)
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.jxtBabyId && this.props.jxtBabyId != this.jxtBabyId) {
            this.jxtBabyId = this.props.jxtBabyId
            if (!this.jxtBabyId || !localStorage.adminTelephone)
                return
            this.loadData()
        }
    }

    //处理加载
    loadData() {
        loginJxt(this.jxtBabyId, (status) => {
            if (status) {
                this.getList()
            } else {
                this.setState({
                    dataLoad: 0,
                    dataNull: 1
                })
            }
            if (this.props.integral)
                integralSwitch({
                    token: localStorage.appToken,
                    schoolName: localStorage.schoolName,
                    range: this.props.sign ? 1 : 2
                }, function(status, data) {
                    this.props.integral(status)
                }.bind(this))
        })
    }

    //最新动态跳转
    DetailUrl(url) {
        if (!url)
            return
        delete sessionStorage.mapinit
        let data = `wherefrom=weixin&appToken=${localStorage.appToken}&appType=1&phone=${localStorage.adminTelephone}&userid=${this.jxtBabyId}`
        if (localStorage.teacher == 1)
            data = `wherefrom=weixin&appToken=${localStorage.appToken}&appType=${[2, 3, 1][this.jxtBabyId-1]}&phone=${localStorage.userphone}`
        location.href = goJxtUrl + '/jiaxiaotong/#' + url + '?' + data;
    }

    //忽略操作
    closeMsg(e) {
        let obj = e.currentTarget.children[0]
        const clsName = obj.className;
        if (document.querySelector('.newmsg i.show'))
            document.querySelector('.newmsg i.show').className = ''
        if (clsName == '') {
            obj.className = 'show'
        } else {
            obj.className = ''
        }
    }

    //获取数据
    getList() {
        if (!sessionStorage.ticket)
            return
        let rct = this;
        let data = `method=ajaxgetRecentNews&jybTicket=${sessionStorage.ticket}&pageNo=1&pageSize=1`;
        $.ajax({
            url: goJxtUrl + '/jxt-commonbackground/ajaxSuiXun.do?' + data,
            //data: data,
            type: 'get',
            dataType: 'json',
            success: function(res) {
                if (res.code == 0) {
                    let dataNull = 0
                    if (res.rs.length == 0) {
                        dataNull = 1
                    }
                    rct.setState({
                        dataLoad: 0,
                        dataList: res.rs,
                        dataNull
                    })
                } else {
                    Toast.toast(res || res.msg);
                    rct.setState({
                        dataLoad: 0,
                        dataNull: 1
                    })
                }
                // setTimeout(() => {
                //     document.getElementById('nsgnotop').style.marginTop = 0
                // }, 1000)
            },
            error: function() {
                rct.setState({
                    dataLoad: 0,
                    dataNull: 1
                })
            }
        })
    }

    //忽略请求
    closeMsgOk(id, index) {
        let rct = this;
        let data = `method=ajaxMarkReaded&jybTicket=${sessionStorage.ticket}&recentNewsid=${id}`;
        $.ajax({
            url: goJxtUrl + '/jxt-commonbackground/ajaxSuiXun.do?' + data,
            type: 'get',
            //data: data,
            dataType: 'json',
            success: function(res) {
                if (res.code == 0) {
                    Toast.toast('消息已忽略', 1000)
                    rct.getList();
                } else {
                    Toast.toast('操作错误')
                }
            },
            error: function() {
                Toast.toast('操作错误')
            }
        })
    }


    render() {
        const {
            dataLoad,
            dataNull,
            dataList
        } = this.state

        const dataTagList = dataList.map((item, index) => {
            if (this.props.length && index >= this.props.length)
                return
            let btn = null
            let url = null
            let haspic = false
            let title = '标题'
            let content = '内容'
            let detail = item.content
            let childtype = detail.childtype
            switch (item.businessType) {
                case '校内公告':
                    title = '公告标题'
                    content = '公告内容'
                    url = '/NtcDetail/' + item.businessId
                    detail.content = '点击进入详情查看>>'
                    break;
                case '家庭作业': //家庭作业
                    title = '作业标题'
                    content = '作业内容'
                    url = '/TaskDetail/' + item.businessId;
                    break;
                case '班级相册':
                    haspic = true
                    btn = '回复'
                    url = '/AlbumDetail/' + detail.dirId + '/' + detail.classid + '/' + encodeURIComponent(detail.dir) + '/' + encodeURIComponent(item.dirRemark || '暂无描述') + '/false/' + item.businessId
                    break;
                case '请假信息':
                    title = '请假类型'
                    content = '请假原因'
                    childtype = '请假批复通知'
                    detail.title = detail.checkType1
                    detail.content = detail.content_p
                    detail.dateFrom = detail.dateFrom.replace(/\-/g, '.')
                    detail.dateTo = detail.dateTo.replace(/\-/g, '.')
                    switch (detail.checkType2) {
                        case '1':
                            detail.checkType2 = '同意'
                            break;
                        case '2':
                            detail.checkType2 = '不同意'
                            break;
                        default:
                            detail.checkType2 = '审批中'
                            break;
                    }
                    url = '/LeaveDetail/' + item.businessId + '/' + encodeURIComponent(detail.rolename) +
                        '/' + encodeURIComponent(detail.checkType1) + '/' + detail.dateFrom + '/' + detail.dateTo + '/' + encodeURIComponent(detail.checkType2) + '/' + encodeURIComponent(detail.content_p || '无') + '/' + encodeURIComponent(detail.content_t || '无');
                    break;
                case '成绩管理': //成绩管理
                    childtype = '成绩发布通知'
                    title = '考试名称'
                    content = '考试类型'
                    detail.content = detail.testType
                    let isKT = detail.testType == '统考成绩' ? true : false
                    url = '/ScoreDetail/' + item.businessId + '/' + isKT;
                    break;
                case '成长记录':
                    btn = '回复'
                    haspic = true
                    childtype = '评论提醒'
                    url = '/GrowthRecordDetails/' + item.businessId + '/true';
                    break;
                case '班级通知':
                    break;
                default:
                    url = '/';
                    Toast.toast('获取数据异常')
                    break;
            }

            return (
                <li>
                    <div className='type'>
                        <title>{childtype}</title>
                        <time>{getLocalTime(item.crateTime.replace(/\-/g,'/'))}</time>
                        <a onClick={this.closeMsg.bind(this)} ><i onClick={this.closeMsgOk.bind(this,item.id,index)}></i></a>
                    </div>
                    <div className={haspic?'content haspic':'content'} onClick={this.DetailUrl.bind(this,url)}>
                        {/*btn?<span className='btnlink'>{btn}</span>:''*/}
                        {!haspic?
                        <div>
                            {detail.title?<div className='text-els'>{title}：{detail.title}</div>:null}
                            {detail.dateFrom?<div className='text-els2'>请假时间：{detail.dateFrom + '-' + detail.dateTo}</div>:''}
                            <div className='text-els2' style={{display:detail.title?null:'block'}}>{content}：{detail.content}</div>
                            {detail.checkType2?<div className='text-els2'>审批状态：{detail.checkType2}</div>:''}
                            {detail.content_t?<div className='text-els2'>老师回复：{detail.content_t}</div>:''}
                            {detail.needFinishTime?<div className='text-els2'>完成时间：{detail.needFinishTime}</div>:''}
                            {detail.score?<div className='text-els2'>考试分数：{detail.score}</div>:''}
                        </div>:
                        <div>
                            <img className='imghead' src={imgHead} />
                            <div className='username'><span>{detail.username||detail.photoUserName}</span>{childtype=='点赞提醒'?'赞了你的照片':''}</div>
                            {childtype=='评论提醒'?
                                <div className='comment'>{detail.comment||detail.photoComment}</div>:''
                            }
                            <div className='piccontent' style={{minHeight:detail.fileId?'80px':'none'}}>
                                {detail.fileId?<div className='photo' style={{backgroundImage:'url('+AjaxUploadImgUrl+detail.fileId.split(',')[0]+')'}}></div>:''}
                                <div className='text-els2'>{detail.photoContent||detail.fileRemark}</div>
                            </div>
                        </div>}
                    </div>
                </li>
            )
        })

        return (
            <div id='nsgnotop'>
                <div className='newmsg'>
                    {
                    dataLoad==1?
                    <div className='datastatus'>
                         <span className='ing'>正在获取最新动态...</span>
                    </div>:''}
                    {
                        dataNull==1?
                    <div className='newstip'>
                        <p className='hy'>欢迎使用随寻通</p>
                        <p className='zw'>暂无最新动态</p>
                    </div>:
                    <div>
                        <ul className='list' id='scroll'>
                            {dataTagList}
                        </ul>
                        {dataTagList!=''?<div className='morelink' onClick={this.DetailUrl.bind(this,'/news')}>更多动态信息>></div>:''}
                    </div>
                    }
                </div>
            </div>
        )
    }
}
